package com.gzy.fisherybackend.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.gzy.fisherybackend.common.BaseResponse;
import com.gzy.fisherybackend.common.ErrorCode;
import com.gzy.fisherybackend.exception.BusinessException;
import com.gzy.fisherybackend.model.dto.FishDistributionAddRequest;
import com.gzy.fisherybackend.model.dto.FishDistributionUpdateRequest;
import com.gzy.fisherybackend.model.entity.FishDistribution;
import com.gzy.fisherybackend.service.FishDistributionService;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/fish-distributions")
public class FishDistributionController {

    @Resource
    private FishDistributionService fishDistributionService;

    /**
     * 获取所有鱼类分布地区
     */
    @GetMapping
    public BaseResponse<List<FishDistribution>> getAllFishSpecies() {
        // 创建查询条件，按创建时间倒序排序
        QueryWrapper<FishDistribution> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc("create_time");
        // queryWrapper.last("ORDER BY create_time DESC, id DESC");
        
        List<FishDistribution> fishSpeciesList = fishDistributionService.list(queryWrapper);
        
        // 处理鱼类列表，将"/"分隔的字符串转换为List
        for (FishDistribution distribution : fishSpeciesList) {
            String fishSpecies = distribution.getFishSpecies();
            if (fishSpecies != null && fishSpecies.contains("/")) {
                // 将"/"分隔的字符串转换为List
                List<String> speciesList = Arrays.asList(fishSpecies.split("/"));
                distribution.setFishSpeciesList(speciesList); // 需要在实体类中添加这个字段
            }
        }
        
        return BaseResponse.success(fishSpeciesList);
    }

    /**
     * 获取所有鱼类种类数量
     */
    @GetMapping("/total")
    public BaseResponse<Long> getFishDistributionCount() {
        QueryWrapper<FishDistribution> queryWrapper = new QueryWrapper<>();
        Long totalCount = fishDistributionService.count(queryWrapper);
        return BaseResponse.success(totalCount);
    }


    /**
     * 添加新的鱼类分布地区
     */
    @PostMapping
    public BaseResponse<Long> addFishDistribution(@RequestBody FishDistributionAddRequest fishDistributionAddRequest) {
        if (fishDistributionAddRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        
        FishDistribution fishDistribution = new FishDistribution();
        BeanUtils.copyProperties(fishDistributionAddRequest, fishDistribution);
        
        // 处理鱼类列表，确保以"/"分隔存储
        String fishSpecies = fishDistribution.getFishSpecies();
        if (fishSpecies != null) {
            // 如果前端传来的是数组或列表，转换为"/"分隔的字符串
            if (fishSpecies.contains(",") && !fishSpecies.contains("/")) {
                fishDistribution.setFishSpecies(fishSpecies.replace(",", "/"));
            }
        }
        
        // 设置创建和更新时间
        Date now = new Date();
        fishDistribution.setCreateTime(now);
        fishDistribution.setUpdateTime(now);
        fishDistribution.setIsDelete(0);
        
        boolean result = fishDistributionService.save(fishDistribution);
        if (!result) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR);
        }
        
        return BaseResponse.success(fishDistribution.getId());
    }

    /**
     * 更新鱼类分布地区
     */
    @PutMapping("/{id}")
    public BaseResponse<Boolean> updateFishDistribution(@PathVariable Long id, @RequestBody FishDistributionUpdateRequest fishDistributionUpdateRequest) {
        if (id <= 0 || fishDistributionUpdateRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        
        FishDistribution fishDistribution = fishDistributionService.getById(id);
        if (fishDistribution == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        
        BeanUtils.copyProperties(fishDistributionUpdateRequest, fishDistribution);
        
        // 处理鱼类列表，确保以"/"分隔存储
        String fishSpecies = fishDistribution.getFishSpecies();
        if (fishSpecies != null) {
            // 如果前端传来的是数组或列表，转换为"/"分隔的字符串
            if (fishSpecies.contains(",") && !fishSpecies.contains("/")) {
                fishDistribution.setFishSpecies(fishSpecies.replace(",", "/"));
            }
        }
        
        fishDistribution.setId(id);
        fishDistribution.setUpdateTime(new Date());
        
        boolean result = fishDistributionService.updateById(fishDistribution);
        if (!result) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR);
        }
        
        return BaseResponse.success(true);
    }

    /**
     * 删除鱼类分布
     */
    @DeleteMapping("/{id}")
    public BaseResponse<Boolean> deleteFishDistribution(@PathVariable Long id) {
        if (id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        
        boolean result = fishDistributionService.removeById(id);
        if (!result) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR);
        }
        
        return BaseResponse.success(true);
    }
    
    /**
     * 获取鱼类分布详情
     */
    @GetMapping("/{id}")
    public BaseResponse<FishDistribution> getFishDistributionById(@PathVariable Long id) {
        if (id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        
        FishDistribution fishDistribution = fishDistributionService.getById(id);
        if (fishDistribution == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        
        // 处理鱼类列表，将"/"分隔的字符串转换为List
        String fishSpecies = fishDistribution.getFishSpecies();
        if (fishSpecies != null && fishSpecies.contains("/")) {
            List<String> speciesList = Arrays.asList(fishSpecies.split("/"));
            fishDistribution.setFishSpeciesList(speciesList);
        }
        
        return BaseResponse.success(fishDistribution);
    }
} 